package com.mine.frame.mylandemo.utils

/**
 * company 广东玛格家居有限公司
 * @author smoker
 * @Date 2021/12/24
 * Description:
 * 计算机存储：最小单位是字节,存储顺序(小端模式)为低位字节在前、高位在后
 */
object MyConvertUtils {

    /**
     * 默认的转化
     * Int转byte[]
     * 低位在前 ，高位在后
     * 3  ==> 03 00 00 00
     * 10 ==> 0A 00 00 00
     */
    fun intTo4BytesLowHigh(value: Int): ByteArray {
        val src = ByteArray(4)
        src[0] = (value and 0xFF).toByte()
        src[1] = (value shr 8 and 0xFF).toByte()
        src[2] = (value shr 16 and 0xFF).toByte()
        src[3] = (value shr 24 and 0xFF).toByte()
        return src
    }


    /**
     * Int转byte[]
     * 高位在前 ，低位在后
     * 3  ==> 00 00 00 03
     * 10 ==> 00 00 00 0A
     */
    fun intTo4BytesHighLow(n: Int): ByteArray {
        return byteArrayOf(
            (n ushr 24 and 0xff).toByte(), (n ushr 16 and 0xff).toByte(),
            (n ushr 8 and 0xff).toByte(), (n and 0xff).toByte()
        )
    }


    /**
     * 整型数据拆分为长度为2的字节数组，低8位存放在序号小的元素，高8位存放在序号大的元素中(小端存储)
     * 低位在前，高位在后
     * @param data
     * @return
     */
    fun intTo2BytesLowHigh(data: Int): ByteArray{
       /* val byteArray = ByteArray(2)
        byteArray[0] = data.toByte()
        byteArray[1] = (data shr 8).toByte()*/
        return byteArrayOf(
            (data and 0xff).toByte(),  (data shr 8).toByte()
        )
    }

    /**
     * 将两个字节拼接还原成有符号的整型数据
     * 数据域中的数据都按小端存储，示例：数据0x1234，则Byte0为0x34,Byte1为0x12
     * @param lowByte   低位
     * @param highByte  高位
     * @return
     */
    fun twoBytesToInt(lowByte: Byte, highByte: Byte): Int {
        var result = highByte.toInt()
        result = result shl 8 or (0x00FF and lowByte.toInt())
        return result
    }



}